package com.haiyou.dc.design.代理模式;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Test动态代理 {

    public static void main(String[] args) {
        Lenovo lenovo = new Lenovo();

        SaleComputer proxySale = (SaleComputer) Proxy.newProxyInstance(lenovo.getClass().getClassLoader()
                , lenovo.getClass().getInterfaces()
                , new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                        System.out.println("方法执行了...");
                        if (method.getName().equals("sale")) {
                            double money = (double) args[0];
                            System.out.println(money);
                            money = money * 0.85;
                            System.out.println("专车接你......");
                            String invoke = (String) method.invoke(lenovo, money);
                            return invoke + "_鼠标垫";
                        }

                        Object obj = method.invoke(lenovo, args);
                        return obj;
                    }
                });

        String sale = proxySale.sale(124.9);
        System.out.println(sale);
    }
}

interface SaleComputer {
    String sale(double money);

    String show();
}

class Lenovo implements SaleComputer {

    @Override
    public String sale(double money) {
        System.out.println("销售联想电脑" + money + "多少钱");
        return "联想电脑";
    }

    @Override
    public String show() {
        return "显示联想电脑";
    }
}